<?php

namespace app\api\model;

use think\Db;

class Product extends BaseModel
{
    protected $hidden = ['delete_time', 'from', 'create_time', 'update_time', 'pivot'];

    //组装 URL ,将 URL 变为绝对路径
    protected function getMainImgUrlAttr($value, $data)
    {
        return $this->getUrl($value, $data);
    }

    /**
     * 获取最新的 $count 条商品信息
     * @param $count
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getRecent($count)
    {
        return self::limit($count)->order('create_time desc')->select();
    }

    /**
     * 根据分类 ID 获取商品信息
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getAllProductsByCategoryID($id)
    {
        return self::where('category_id', '=', $id)->select();
    }


    /**
     * 根据产品 ID 找到对应的产品
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getProductInfoByID($id)
    {
        return self::with(['imgs' => function($query) {
            $query->with('imgUrl')->order(['order' => 'ASC']);
        }])->with(['properties'])->find($id);
    }

    /**
     *
     * @return \think\model\relation\HasMany
     */
    public function imgs()
    {
        return $this->hasMany('ProductImage', 'product_id', 'id');
    }
    
    public function properties()
    {
        return  $this->hasMany('ProductProperty', 'product_id', 'id');
    }
}